﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Linq.Dynamic;
using SDT.Model;
using SDT.Lib.Common;
using SDT.Lib.Paging;
using SDT.Admin.ViewModels;
using SDT.Admin.Properties;
using System.IO;

namespace SDT.Admin.Controllers
{
    public class OrderController : Controller
    {
        //
        // GET: /Order/
        SDTDataContext eDataContent = new SDTDataContext();
        public ActionResult Index()
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Product))
                {
                    //sap xep
                    string order = UserState.getUserStateFromRequest("order.order", "order", "id").ToString();
                    string orderDir = UserState.getUserStateFromRequest("order.orderDir", "orderDir", "desc").ToString();
                    var pageNumber = Convert.ToInt32(UserState.getUserStateFromRequest("order.PageNumber", "page", 1));
                    var pageIndex = pageNumber - 1;
                    int pageSize = int.Parse(UserState.getUserStateFromRequest("order.pageSize", "PageSize", 20).ToString());

                    int paymentID = Convert.ToInt32(UserState.getUserStateFromRequest("order.ddlPayment", "ddlPayment", 0));
                    int statusID = Convert.ToInt32(UserState.getUserStateFromRequest("order.ddlStatus", "ddlStatus", 0));
                    int typeID = Convert.ToInt32(UserState.getUserStateFromRequest("order.ddlOrderType", "ddlOrderType", -1));
                    string keyword = UserState.getUserStateFromRequest("order.Keyword", "Keyword", "").ToString();
                    
                    var fromDate = DateTime.MinValue;
                    var toDate = DateTime.MinValue;
                    var inYear = 0;
                    if (Request["durationType"] == "0")
                    {
                        fromDate = Utils.ParseDateTime(UserState.getUserStateFromRequest("order.FromDate", "fromDate", DateTime.MinValue).ToString(), new System.Globalization.CultureInfo("vi-VN"));
                        toDate = Utils.ParseDateTime(UserState.getUserStateFromRequest("order.ToDate", "toDate", DateTime.MinValue).ToString(), new System.Globalization.CultureInfo("vi-VN"));

                        // Thiết lập từ đầu ngày đến cuối ngày
                        fromDate =fromDate!=DateTime.MinValue? new DateTime(fromDate.Year, fromDate.Month, fromDate.Day, 0, 0, 0):fromDate;
                        toDate = toDate != DateTime.MinValue ? new DateTime(toDate.Year, toDate.Month, toDate.Day, 23, 59, 59) : toDate;
                    }
                    else
                    {
                        fromDate = new DateTime(Convert.ToInt32(UserState.getUserStateFromRequest("order.InYear", "inYear", DateTime.MinValue.Year)), 1, 1, 0, 0, 0);
                        inYear = fromDate.Year != DateTime.MinValue.Year ? fromDate.Year : 0;
                        toDate = inYear > 0 ? new DateTime(Convert.ToInt32(UserState.getUserStateFromRequest("order.InYear", "inYear", DateTime.Now.Year)), 12, 31, 23, 59, 59) : DateTime.MinValue;
                    }
                    // tra ve cac danh sach
                    var l = OrderManager.GetListInAdmin(paymentID, statusID,typeID, fromDate, toDate, keyword, order, orderDir, pageIndex, pageSize);
                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;
                    //hien thi
                    return View(new OrderIndexViewModels
                    {
                        Orders = l,
                        Keyword = keyword,
                        Payments=eDataContent.Payments.ToList(),
                        OrderStatus=Utils.StringToDictionaryIntString(Settings.Default.OrderStatus,","),
                        OrderTypes = Utils.StringToDictionaryIntString(Settings.Default.OrderType, ","),
                        PaymentID=paymentID,
                        StatusID=statusID,
                        TypeID=typeID,
                        OperationDurations=OrderManager.OperationDuration(),
                        FromDate=fromDate,
                        ToDate=toDate,
                        InYear=inYear

                    });
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Order/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Product))
                {                    
                    OrderEditViewModels p = new OrderEditViewModels();
                    p.Order=eDataContent.Orders.Where(e => e.ID == id).SingleOrDefault();
                    p.OrderStatus = Utils.StringToDictionaryIntString(Settings.Default.OrderStatus, ",");
                    p.OrderTypes = Utils.StringToDictionaryIntString(Settings.Default.OrderType, ",");
                    return View(p);
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        public ActionResult Export(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Product))
                {
                    OrderEditViewModels p = new OrderEditViewModels();
                    p.Order = eDataContent.Orders.Where(e => e.ID == id).SingleOrDefault();
                    p.OrderStatus = Utils.StringToDictionaryIntString(Settings.Default.OrderStatus, ",");
                    p.OrderTypes = Utils.StringToDictionaryIntString(Settings.Default.OrderType, ",");
                    return View(p);
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }

        //
        // GET: /Order/Edit/5
 
        public ActionResult Edit(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Product))
                {                    
                    OrderEditViewModels p = new OrderEditViewModels();
                    p.Order=eDataContent.Orders.Where(e => e.ID == id).SingleOrDefault();
                    p.OrderStatus = Utils.StringToDictionaryIntString(Settings.Default.OrderStatus, ",");
                    p.OrderTypes = Utils.StringToDictionaryIntString(Settings.Default.OrderType, ",");
                    return View(p);
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Order/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, OrderEditViewModels p)
        {
            try
            {
                // TODO: Add update logic here
                if (UserManager.CheckRole(RoleSystem.Product))
                {
                    p.Order = eDataContent.Orders.Where(e => e.ID == id).SingleOrDefault();
                    UpdateModel(p);
                    var deliverDate = Request["txtDeliverDate"] != null && Request["txtDeliverDate"] != string.Empty ? Utils.ParseDateTime(Request["txtDeliverDate"], new System.Globalization.CultureInfo("vi-VN")) : (DateTime?)null;
                    p.Order.DeliveryDate = deliverDate > p.Order.AddDate ? deliverDate : null;
                    p.OrderStatus = Utils.StringToDictionaryIntString(Settings.Default.OrderStatus, ",");
                    p.OrderTypes = Utils.StringToDictionaryIntString(Settings.Default.OrderType, ",");
                    int statusID = Convert.ToInt32(UserState.getUserStateFromRequest("order.ddlStatus", "ddlStatus", 0));
                    p.Order.Status = statusID;
                    eDataContent.SubmitChanges();
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch(Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // GET: /Order/Delete/5
 
        public ActionResult Delete(int id)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Product))
                {
                    var item = eDataContent.Orders.Single(e => e.ID == id);
                    return View(item);
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Order/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                if (UserManager.CheckRole(RoleSystem.Product))
                {

                    var item = eDataContent.Orders.Single(e => e.ID == id);

                    if (item != null)
                    {
                        eDataContent.OrderDetails.DeleteAllOnSubmit(item.OrderDetails);
                        eDataContent.Orders.DeleteOnSubmit(item);
                        eDataContent.SubmitChanges();
                    }
                    return RedirectToAction("Index");
                }
                else
                {
                    ViewData[Messages.MessageInfo] = Messages.NOT_PERMIT;
                    return View();
                }
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
